package com.store.satring.web;
import com.store.satring.dos.GeneralLedger;
import com.store.satring.dos.GeneralLedgerDetail;
import com.store.satring.dos.Invoice;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.joda.time.format.DateTimeFormat;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RequestMapping("/generalledgers")
@Controller
public class GeneralLedgerController {

	@RequestMapping(params = { "find=ByGLNoEquals", "form" }, method = RequestMethod.GET)
    public String findGLByGLNoEqualsForm(Model uiModel) {
        return "generalledgers/findGLByGLNoEquals";
    }

	@RequestMapping(params = "find=ByGLNoEquals", method = RequestMethod.GET)
    public String findGLByGLNoEquals(@RequestParam("glNo") String glNo, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
            int sizeNo = size == null ? 10 : size.intValue();
            List<GeneralLedger> glSearchResults = GeneralLedger.findGLByGLNoEquals(glNo);
            uiModel.addAttribute("generalledgers", glSearchResults);
            float nrOfPages = (float) glSearchResults.size() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        addDateTimeFormatPatterns(uiModel);
        return "generalledgers/list";
    }

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid GeneralLedger generalLedger, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
		Long invoiceId = generalLedger.getInvoice().getId();
		Integer glNo = GeneralLedger.getGLNo(invoiceId);
        if (bindingResult.hasErrors() || glNo != null) {
        	if(glNo != null){
        		bindingResult.addError(new ObjectError("GL already exists.", "GL(Number : "+glNo+") already exixsts for selected Invoice"));	
        	}
            populateEditForm(uiModel, generalLedger);
            return "generalledgers/create";
        }
        
        
        uiModel.asMap().clear();
        generalLedger.setInvoiceAmount(generalLedger.getInvoice().getAmount());
        generalLedger.setAdvanceAmount(generalLedger.getInvoice().getAdvanceAmount());
        generalLedger.setBalanceAmount(generalLedger.getInvoice().getAmount() - generalLedger.getInvoice().getAdvanceAmount());
        generalLedger.persist();
        return "redirect:/generalledgers/" + generalLedger.getId().toString() + "?form";
    }

	@RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
		GeneralLedger generalLedger = new GeneralLedger();
		generalLedger.setGlNo(GeneralLedger.getNewGLNo());
		generalLedger.setGlDate(new Date());
        populateEditForm(uiModel, generalLedger);
        List<String[]> dependencies = new ArrayList<String[]>();
        if (Invoice.countInvoices() == 0) {
            dependencies.add(new String[] { "invoice", "invoices" });
        }
        uiModel.addAttribute("dependencies", dependencies);
        return "generalledgers/create";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("generalledger", GeneralLedger.findGeneralLedger(id));
        uiModel.addAttribute("itemId", id);
        return "generalledgers/show";
    }

	@RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("generalledgers", GeneralLedger.findGeneralLedgerEntries(firstResult, sizeNo, sortFieldName, sortOrder));
            float nrOfPages = (float) GeneralLedger.countGeneralLedgers() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("generalledgers", GeneralLedger.findAllGeneralLedgers(sortFieldName, sortOrder));
        }
        addDateTimeFormatPatterns(uiModel);
        return "generalledgers/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid GeneralLedger generalLedger, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, generalLedger);
            return "generalledgers/update";
        }
        uiModel.asMap().clear();
        double glDetailAmount = getGLDetailAmount(generalLedger);
		generalLedger.setTotalPaymentReceived(generalLedger.getAdvanceAmount() + glDetailAmount);
		generalLedger.setBalanceAmount(generalLedger.getInvoiceAmount() - generalLedger.getTotalPaymentReceived() - generalLedger.getAdjustedAmount());
        generalLedger.merge();
        return "redirect:/generalledgers/" + encodeUrlPathSegment(generalLedger.getId().toString(), httpServletRequest) + "?form";
    }

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
		GeneralLedger generalLedger = GeneralLedger.findGeneralLedger(id);
		double glDetailAmount = getGLDetailAmount(generalLedger);
		generalLedger.setTotalPaymentReceived(generalLedger.getAdvanceAmount() + glDetailAmount);
		generalLedger.setBalanceAmount(generalLedger.getInvoiceAmount() - generalLedger.getTotalPaymentReceived() - generalLedger.getAdjustedAmount());
        populateEditForm(uiModel, generalLedger);
        return "generalledgers/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        GeneralLedger generalLedger = GeneralLedger.findGeneralLedger(id);
        generalLedger.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/generalledgers";
    }

	void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("generalLedger_gldate_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale()));
    }

	void populateEditForm(Model uiModel, GeneralLedger generalLedger) {
        uiModel.addAttribute("generalLedger", generalLedger);
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("generalledgerdetails", generalLedger.getGeneralLedgerDetails());
        uiModel.addAttribute("invoices", Invoice.findAllInvoices());
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
	
	private double getGLDetailAmount(GeneralLedger generalLedger) {
		//Update related amounts
        List<GeneralLedgerDetail> generalLedgerDetails = generalLedger.getGeneralLedgerDetails();
        double amount = 0;
        for (GeneralLedgerDetail glDetail : generalLedgerDetails) {
        	amount += glDetail.getAmount();
		}
		return amount;
	}


}
